package com.shi.yibanjia.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.service.SMSService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

import static com.shi.yibanjia.common.constant.RedisConstant.*;

@ConditionalOnProperty(value = "spring.profiles.active", havingValue = "prod")
@Service
public class AliYunSMSServiceImpl implements SMSService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private Config config;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    @Override
    public Result sendSMS(String phone) {
        Client client = null;
        try {
            client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 1. 生成6位随机数验证码
        String randomNumbers = RandomUtil.randomNumbers(6);
        StaticLog.info("手机号验证码: {}", randomNumbers);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(templateCode);
        String templateParam = JSONUtil.toJsonStr(Map.of("code", randomNumbers));
        sendSmsRequest.setTemplateParam(templateParam);
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = client.sendSms(sendSmsRequest);
            // 2. 手机号作为key，将验证码存入redis
            stringRedisTemplate.opsForValue().set(PHONE_CODE + phone, randomNumbers, PHONE_CODE_TTL, TIME_UNIT);
            // {"bizId":"519307913510199572^0","code":"OK","message":"OK","requestId":"4228C778-6195-5C9B-A430-7CDF68BC954A"}
            // System.out.println(JSONUtil.toJsonStr(sendSmsResponse.getBody()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("OK".equals(sendSmsResponse.getBody().code)) {
            return Result.ok();
        } else {
            return Result.fail(sendSmsResponse.getBody().getMessage());
        }
    }
}
